<template>
  <div id="cesiumContainer"></div>
</template>
<script setup>
  import { onMounted } from 'vue'
  import * as Cesium from 'cesium';
  import { PopUpOnWindowPosition } from '../../assets/js/addCesiumPopUp'
  import { CesiumPopup } from "cesium-popup-es6"

  Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJjY2MwYWVlNS1lYTRhLTRlOTYtYTZmYi1mYTU1NzhkYmJiMGYiLCJpZCI6ODQ4ODIsImlhdCI6MTY0NjY0NjU1NH0.lg9M-qvSJiz4sUfkZHZkmKZByNLZICZacC_O_5FqR9A';

  onMounted(() => {
    const cesiumContainer = document.getElementById('cesiumContainer')
    const custom =  new Cesium.ArcGisMapServerImageryProvider({
        url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
      })
    const viewer = new Cesium.Viewer(cesiumContainer, {
          // animation : false,
          //   timeline : false,
          //   baseLayerPicker : false,
          //   geocoder : false,
          //   navigationHelpButton : false,
          //   homeButton : false,
          //   scene3DOnly : true,
          //   fullscreenButton : false,
           animation: false, // 动画小组件
          baseLayerPicker: false, // 图层选择器（底图组件）
          fullscreenButton: false, // 全屏按钮
          geocoder: false, // 地名查找组件，地理编码，搜索按钮
          homeButton: false, // 首页，点击之后试图将跳转到默认视角。地图中心点按钮
          infoBox: false, // 信息框，显示要素的详细信息
          vrButton: false, // VR模式；平面和全景切换按钮
          sceneModePicker: false, // 场景模式选择器,切换2D，3D和哥伦布视图模式
          selectionIndicator: false, // 选择指示器，显示当前选择的要素
          timeline: false, // 时间线，显示时间轴
          navigationHelpButton: false, // 帮助按钮
          navigationInstructionsInitiallyVisible: false, // 导航指示初始化是否可见


          baseLayerPicker: false,
          imageryProvider: custom,
          // 设置cesium世界地形
          terrainProvider: Cesium.createWorldTerrain({
            requestVertexNormals: true,  // 请求水体效果所需要的海岸线数据
            requestWaterMask: true, // 请求地形照明数据
          }),
    })


  //弹窗对象
var popWindow = new PopUpOnWindowPosition(viewer)

//数据
var dataItem = {
    //显示的数据项
    builtDate: '2022-02-02', //成立时间
    belongGrid: 'XX社区第一网格', //所属网格
    gridYuan: '张三丰',
}

//注册点击事件
var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
console.log('===handler====',handler)
handler.setInputAction(function(movement) {
    //获取点击对象
    console.log(movement.position)
        //获取窗口坐标位置
    const windowPosition = movement.position
        //设置弹出窗口的位置
    popWindow.setPositon(
        windowPosition,
        //设置弹窗要显示的内容
        ` <table class="dateIem">
          <tr>
            <td>成立时间：</td>
            <td>${dataItem.builtDate}}</td>
          </tr>
          <tr>
            <td>所属网格：</td>
            <td>${dataItem.belongGrid}</td>
          </tr>
          <tr>
            <td>网格员</td>
            <td>${dataItem.gridYuan}</td>
          </tr>
      </table>`
    )
}, Cesium.ScreenSpaceEventType.LEFT_CLICK)



const action = {
    remove: (popup) => {
        console.log(popup, "被移除了");

    },
    onChange: (popup) => {
        console.log(popup, "移动完成");
    },
    editAttr: (popup) => {
        console.log(popup, "需要编辑属性！");
        popup.setContent("我的内容被改变了！")
    }
}
const cartesian33 = Cesium.Cartesian3.fromDegrees(121.495048, 31.252508, 200)
const html3 = `<div class="title">汽车模型</div>
 <div class="content">我在汽车模型上</div>
 <div class="content">我在汽车模型上22</div>`
 new CesiumPopup(viewer, {
     position: cartesian33, html: html3, className: "earth-popup-imgbg-blue", popPosition: "leftbottom"
 }, action)



    // viewer.camera.setView({
    //   destination: Cesium.Cartesian3.fromDegrees(113.318977, 23.114155, 2000),
    //   orientation: {
    //     heading: Cesium.Math.toRadians(90), // 旋转多少度
    //     pitch: Cesium.Math.toRadians(0), // 倾斜多少度
    //     roll: 0.0
    //   }
    // })
    viewer.camera.setView({
      destination: new Cesium.Cartesian3(1332761, -4662399, 4137888),
      orientation: {
        heading: 0.60, // 旋转多少度
        pitch: -0.66, // 倾斜多少度
        roll: 0.0
      }
    })

    // 添加3D模型
    let city = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
      url: new Cesium.IonResource.fromAssetId(3839),// 'https://www.cesiumcontent.com/api/tilesets/models/3d/CesiumMan/tileset.json'
    }))

    // 为模型添加样式
    let heightStyle = new Cesium.Cesium3DTileStyle({
      color: {
        // 条件判断(根据高度设备不同颜色)
          conditions : [
              ['${height} >= 100', 'color("orange", 0.8)'],
              ['${height} >= 50', 'color("green", 0.4)'],
              ['true', 'color("blue", 0.6)']
          ]
      }
    })
    city.style = heightStyle

    let neiborhoods;
    // geoJson文件加载
    Cesium.GeoJsonDataSource.load('../../../../public/assets/SampleData/sampleNeighborhoods.geojson')
    .then(function(dataSource) {
      // 将数据添加到查看器
      viewer.dataSources.add(dataSource)
      neiborhoods = dataSource.entities
      let neiborhoodEntities = dataSource.entities.values
      for(let i=0;i<neiborhoodEntities.length;i++){
        let entity = neiborhoodEntities[i]
        if(Cesium.defined(entity.polygon)){
          entity.name = entity.properties.neiborhood
          entity.polygon.material = Cesium.color.fromRandom({
            red: 0.1,
            alpha: 0.6,
            minimumGreen: 0.75,
            maximumGreen: 1.0,
            minimumBlue: 0.75,
            maximumBlue: 1.0,
          })
          // BOTH 或 CESIUM_3D_TILE 或 TERRAIN
          entity.polygon.classificationType = Cesium.ClassificationType.TERRAIN;  //区块直接贴在地面上
         // Generate Polygon center(将中心点移到海拔为0的位置)
          var polyPositions = entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
          var polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center;
          polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter);
          entity.position = polyCenter;

          // 生成标签
          entity.label = {
            text: entity.name,
            showBackground : true,
            scale : 0.6,
            horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
            verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
            distanceDisplayCondition : new Cesium.DistanceDisplayCondition(10.0, 8000.0),
            disableDepthTestDistance : 100.0
          }
        }
      }
    })

var kmlOptions = {
        camera : viewer.scene.camera,
        canvas : viewer.scene.canvas,
        // 如果我们想要将几何特征（多边形、线串和线性环）固定在地面上，则为 true。
        clampToGround : true
    };
    //KML文件是谷歌公司创建的一种地标性文件。
    //用于记录某一地点、或连续地点的时间、经度、纬度、海拔等地理信息数据，供GE等有关软件使用。
    // Load geocache points of interest from a KML file
    // Data from : http://catalog.opendata.city/dataset/pediacities-nyc-neighborhoods/resource/91778048-3c58-449c-a3f9-365ed203e914
    var geocachePromise = Cesium.KmlDataSource.load('../../../../public/assets/SampleData/sampleGeocacheLocations.kml', kmlOptions);

    // 将 geocache 广告牌实体添加到场景中并为其设置样式
    geocachePromise.then(function(dataSource) {
        // 将新数据作为实体添加到查看器
        viewer.dataSources.add(dataSource);

        // 获取实体数组
        var geocacheEntities = dataSource.entities.values;

        for (var i = 0; i < geocacheEntities.length; i++) {
            var entity = geocacheEntities[i];
            if (Cesium.defined(entity.billboard)) {
                // 调整垂直原点，使图钉位于地形上
                
                entity.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
                entity.billboard.image = '../../../../public/assets/tagpark.png'
                // entity.billboard.scaleByDistance= new NearFarScalar(10000, 1.0, 20000, 0.0)
                // 禁用标签以减少混乱
                entity.label = {
                    text: "sssssssssss",
                    // scaleByDistance: new NearFarScalar(10000, 1.0, 20000, 0.0),
                    showBackground : true,
                    scale : 0.6,
                    horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
                    distanceDisplayCondition : new Cesium.DistanceDisplayCondition(10.0, 8000.0),
                    disableDepthTestDistance : 100.0
                  };
                // 添加距离显示条件
                entity.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(10.0, 20000.0);
                // 以度为单位计算纬度和经度
                var cartographicPosition = Cesium.Cartographic.fromCartesian(entity.position.getValue(Cesium.JulianDate.now()));
                var latitude = Cesium.Math.toDegrees(cartographicPosition.latitude);
                var longitude = Cesium.Math.toDegrees(cartographicPosition.longitude);
                // 修改描述
                var description = '<table style="background:red;" class="cesium-infoBox-defaultTable cesium-infoBox-defaultTable-lighter"><tbody>' +
                    '<tr><th>' + "Longitude" + '</th><td>' + longitude.toFixed(5) + '</td></tr>' +
                    '<tr><th>' + "Latitude" + '</th><td>' + latitude.toFixed(5) + '</td></tr>' +
                    '<tr><th>' + "实时人流" + '</th><td>' + Math.floor(Math.random()*20000)  + '</td></tr>' +
                    '<tr><th>' + "安全等级" + '</th><td>' + Math.floor(Math.random()*5)  + '</td></tr>' +
                    '</tbody></table>';
                entity.description = description;
            }
        }
    });


// 从czml文件加载飞行路径
  var dronePromise = Cesium.CzmlDataSource.load('../../../../public/assets/SampleData/sampleFlight.czml');

  // 无人机实体
  var drone;
  dronePromise.then(function(dataSource){
    viewer.dataSources.add(dataSource);
    drone = dataSource.entities.getById('Aircraft/Aircraft1');
    drone.model = {
      // uri:'../../../../public/assets/SampleData/Models/CesiumDrone.gltf',
      uri:'../../../../public/assets/SampleData/Models/ferrari2.gltf',
      minimumPixelSize:100,
      maximumScale:1000,
      silhouetteColor:Cesium.Color.WHITE, // 轮廓颜色
      silhouetteSize:2  //轮廓线宽度
    }

    drone.orientation = new Cesium.VelocityOrientationProperty(drone.position);
    drone.viewFrom = new Cesium.Cartesian3(0,-30,30)
    // 调整时钟让模型运动
    viewer.clock.shouldAnimate = true;
  })





  })
</script>

<style>
#app,
html,
body,
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>
